package com.devmarvel.creditcardentry.fields;

import com.devmarvel.creditcardentry.ResourceTable;
import com.devmarvel.creditcardentry.internal.CreditCardUtil;
import ohos.agp.components.AttrSet;
import ohos.agp.render.Paint;
import ohos.agp.utils.Rect;
import ohos.app.Context;

public class ExpDateText extends CreditEntryFieldBase {

    private String previousString;

    private String mHelperText;

    public ExpDateText(Context context) {
        super(context);
        init();
    }

    public ExpDateText(Context context, AttrSet attrs) {
        super(context, attrs);
        init();
    }

    public ExpDateText(Context context, AttrSet attrs, String defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    void init() {
        super.init();
        setHint("MM/YY");
        Paint textPaint = new Paint();
        textPaint.setTextSize(getTextSize());
        Rect bounds = textPaint.getTextBounds("MMMMM");
        setMinWidth(bounds.getWidth() + (2 * HORIZONTAL_PADDING) + PADDING_OFFSET);
        setMinHeight(bounds.getHeight());
    }

    /* TextWatcher Implementation Methods */
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        previousString = s.toString();
    }

    public void afterTextChanged(String s) {
        // if delete occurred do not format
        if (s.length() > previousString.length()) {
            formatAndSetText(s);
        }
    }

    public void formatAndSetText(String updatedString) {
        watcherEnabled = false;
        String formatted = CreditCardUtil.formatExpirationDate(updatedString);
        this.setText(formatted);
        watcherEnabled = true;

        if (formatted.length() == 5) {
            setValid(true);
            String remainder = null;
            if (updatedString.startsWith(formatted)) {
                remainder = updatedString.replace(formatted, "");
            }
            delegate.onExpirationDateValid(remainder);
        } else if (formatted.length() < updatedString.length()) {
            setValid(false);
            delegate.onBadInput(this);
        }
    }

    @Override
    public void setHelperText(String helperText) {
        mHelperText = helperText;
    }

    @Override
    public String getHelperText() {
        return (mHelperText != null ? mHelperText : context.getString(ResourceTable.String_ExpirationDateHelp));
    }

}
